import smtplib
import time
import traceback
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from constants.MyConstant import DIR_NAME

from Config import global_config
from util import LogUtils


class HandEmail:
    def __init__(self):
        self.smtp_server = global_config.get('config', 'smtp_server')
        self.from_mail = global_config.get('config', 'from_mail')
        self.mail_pass = global_config.get('config', 'mail_pass')
        self.to_mail = global_config.get('config', 'to_mail')
        self.title = global_config.get('config', 'title')
        self.body_content = global_config.get('config', 'body_content')
        try:
            self.send()
        except Exception as e:
            LogUtils.log('error.log', traceback.format_exc())
            print(e)

    def send(self):
        today = time.strftime("%Y-%m-%d", time.localtime())
        path = DIR_NAME + '/' + '可转债' + today + '-03.csv'
        fileName = '可转债' + today + '.csv'
        self.sendEmail(title=self.title + today, text=self.body_content, send=self.from_mail,
                       to=self.to_mail.split(','),
                       passwd=self.mail_pass, smtp_server=self.smtp_server,
                       path=path,
                       fileName=fileName)

    def sendEmail(self, title, text, send, to, passwd, smtp_server, path, fileName):
        '''
        发送带附件的邮件
        :param title: 邮件标题
        :param text: 邮件正文
        :param send: 发送者邮箱
        :param passwd: 授权码
        :param to: 接收者邮箱
        :param smtp_server: 发送邮件的服务器
        :param path: 需要发送的附件
        :return:
        '''
        msg = MIMEMultipart()
        msg['From'] = send
        msg['To'] = Header(','.join(to))
        # 文字部分
        msg['Subject'] = Header(title, 'utf-8')  # 主题
        att = MIMEText(text, "html", 'utf-8')
        # att = MIMEText(text, 'plain', 'utf-8')
        msg.attach(att)
        # 附件
        att = MIMEText(open(path, 'rb').read(), 'base64', 'utf-8')
        att["Content-Type"] = 'application/octet-stream'
        att.add_header('Content-Disposition', 'attachment', filename=fileName)  # filename可随意取名
        msg.attach(att)

        server = smtplib.SMTP()
        server.connect(smtp_server)  # 连接smtp邮件服务器
        # set_debuglevel()是用来调试的。参数值为1表示开启调试模式，参数值为0关闭调试模式
        server.set_debuglevel(1)
        server.ehlo(smtp_server)
        server.login(send, passwd)  # 登录smtp邮件服务器
        server.sendmail(send, to, msg.as_string())  # 发送
        server.close()  # 关闭


def sendMail():
    HandEmail()


if __name__ == '__main__':
    handleEmail = HandEmail()
